/*
 * Copyright (c) 2020-2021 imlzw@vip.qq.com jweb.cc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cc.jweb.adai.web.websocket.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.websocket.Session;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class LogWebSocketService {
    private static final Logger logger = LoggerFactory.getLogger(LogWebSocketService.class);
    private static final Map<String, Session> sessionCache = new HashMap<String, Session>();

    public static void addSession(Session session) {
        sessionCache.put(session.getId(), session);
    }

    public static void removeSession(Session session) {
        sessionCache.remove(session.getId());
    }

    public synchronized static void sendMessage(String message) {
        for (String key : sessionCache.keySet()) {
            Session session = sessionCache.get(key);
            if (session.isOpen()) {
                try {
                    session.getBasicRemote().sendText(message);
                } catch (IOException e) {
                    logger.error("向Session【{}】发送消息异常！", session.getId());
                }
            }
        }
    }

    public static void sendError(Throwable throwable) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        PrintStream pout = null;
        try {
            pout = new PrintStream(out, true, "UTF-8");
            throwable.printStackTrace(pout);
            String ret = out.toString("UTF-8");
            sendMessage(ret);
        } catch (UnsupportedEncodingException e) {
            logger.error("发送消息异常！", e);
        } finally {
            if (pout != null) {
                try {
                    pout.close();
                } catch (Exception e) {
//                    logger.error("关闭流失败！！", e);
                }
            }
            try {
                out.close();
            } catch (Exception e) {
//                logger.error("关闭流失败！！", e);
            }
        }
    }

    /**
     * 获取输出流
     * @return
     */
    public static OutputStream getMessageOutputStream() {
        return new OutputStream() {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

            @Override
            public void write(int b) throws IOException {
                byteArrayOutputStream.write(b);
                if (b == 10) {
                    String line = byteArrayOutputStream.toString("UTF-8");
                    byteArrayOutputStream.reset();
                    sendMessage(line);
                }

            }
        };
    }

    public static Map<String, Session> getSessionCache() {
        return sessionCache;
    }
}
